package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysLeave;
import com.ruoyi.system.mapper.SysLeaveMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 老人请假状态更新
 * @author jinyao
 */
@Component("elderLeaveStatus")
public class ElderLeaveStatus {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysLeaveMapper sysLeaveMapper;

    private static final Logger log = LoggerFactory.getLogger(ElderStatusTask.class);

    public void updateElderLeaveStatus() {
        log.info("老人请假状态更新 开始");

        //这里应该调用服务层的方法，更新老人在院状态
        SysUser sysUser = new SysUser();
        sysUser.setDelFlag("0");
        //查询所有老人
        List<SysUser> sysUsers = sysUserMapper.selectElderList(sysUser);
        //获取所有老人的id
        Set<Long> collect = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());
        Date now = new Date();
        SysLeave sysLeave = new SysLeave();
        sysLeave.setDelFlag("0");
        sysLeave.setStatus("1");
        sysLeave.setElderUserIds(collect);
        List<SysLeave> sysLeaves = sysLeaveMapper.selectSysLeaveList(sysLeave);
        if (sysLeaves.isEmpty()){
            log.info("没有老人请假信息");
            return;
        }
        Map<Long, List<SysLeave>> collect1 = sysLeaves.stream().collect(Collectors.groupingBy(SysLeave::getElderUserId));
        for (SysUser sysUser1 : sysUsers) {
            //先设定 没请假状态
            sysUser1.setLeaveStatus("0");
            List<SysLeave> sysLeaves1 = collect1.get(sysUser1.getUserId());
            if (sysLeaves1 != null &&  !sysLeaves1.isEmpty()){
               for (SysLeave sysLeave1 : sysLeaves1) {
                   if (now.compareTo(sysLeave1.getStartTime()) >= 0 && now.compareTo(sysLeave1.getEndTime()) <= 0){
                       sysUser1.setLeaveStatus("1");
                       break;
                   }
               }
            }
            sysUserMapper.updateUser(sysUser1);

        }
        log.info("老人请假状态更新 结束");
    }
}
